<?php
require_once 'common.php';

class Photosaic {
	private $api_key	= 'b0f8d50a71159895437b09d8be7a743f';
	private $secret	= '8ac3a346325dac9a';

	function __construct() {

	}

	function FlickrCall($method, $params = array()) {
		$params = array_merge(
				array(
					'api_key'	=> $this->api_key,
					'format'	=> 'php_serial',
					'method'	=> $method
				),
				$params
			);
		$encoded_params = array();
		foreach ($params as $k => $v)
			$encoded_params[] = urlencode($k).'='.urlencode($v);

		$url = 'http://api.flickr.com/services/rest/?'.implode('&', $encoded_params);

		$response = file_get_contents($url);

		return unserialize($response);
	}

	function GetPhotoURL($photo, $size) {
		$url = "http://farm{$photo[farm]}.static.flickr.com/{$photo[server]}/{$photo[id]}_{$photo[secret]}_{$size}.jpg";
		return $url;
	}

	function CreateImage($url) {
		@$im = imagecreatefromjpeg($url);
		return $im;
	}

	function GetRGBAt($image, $x, $y) {
		return imagecolorsforindex($image, imagecolorat($image, $x, $y));
	}

	function AnalyzeColors($image) {
		$colors = array('r' => array(), 'b' => array(), 'g' => array());
		$r = 0;
		$g = 0;
		$b = 0;
		$w = imagesx($image);
		$h = imagesy($image);
		for ($x = 0; $x < $w; $x++) {
			for ($y = 0; $y < $h; $y++) {
				$rgb = $this->GetRGBAt($image, $x, $y);
				$r += $rgb['red'];
				$g += $rgb['green'];
				$b += $rgb['blue'];
				$colors['r'][$rgb['red']]++;
				$colors['g'][$rgb['green']]++;
				$colors['b'][$rgb['blue']]++;
			}
		}

		$s = $w*$h;
		$quality = array('r' => 0, 'g' => 0, 'b' => 0);
		$quality_limit = 30;
		for ($i = 0; $i < 256; $i++) {
			if ($i > $r/$s - $quality_limit && $i < $r/$s + $quality_limit)
				$quality['r'] += $colors['r'][$i];
			if ($i > $g/$s - $quality_limit && $i < $g/$s + $quality_limit)
				$quality['g'] += $colors['g'][$i];
			if ($i > $b/$s - $quality_limit && $i < $b/$s + $quality_limit)
				$quality['b'] += $colors['b'][$i];
		}

		$result = array(	'avg' => array('r' => round($r/$s), 'g' => round($g/$s), 'b' => round($b/$s)),
				'quality' => array('r' => round(100*$quality['r']/$s, 2), 'g' => round(100*$quality['g']/$s, 2), 'b' => round(100*$quality['b']/$s, 2),
					'avg' => round(100*($quality['r'] + $quality['g'] + $quality['b'])/$s/3, 2))
				);

		return $result;
	}
	
	function CacheImage($db, $url,$r,$g,$b,$r_match,$g_match,$b_match,$rgb_match) {
		$url = $db->clean($url);
		$db->query_write("INSERT INTO photo_cache (url, r, g, b, r_match, g_match, b_match, rgb_match, added, last_used) "
				  ."VALUES ('$url',$r,$g,$b,$r_match,$g_match,$b_match,$rgb_match,NOW(),'0000-00-00 00:00:00')");
	}
}
?>